#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import glob
import shutil


def create_link_force(src, des):
    if os.path.exists(des):
        if os.path.realpath(des) == os.path.realpath(src):
            return
        os.remove(des)
    create_link(src, des)


def create_link(src, des):
    if src == des:
        return
    os.symlink(src, des)


def create_path(path):
    if not os.path.exists(path):
        os.makedirs(path)


def create_path_force(path):
    destroy_path(path)
    create_path(path)


def destroy_path(path):
    if os.path.exists(path):
        shutil.rmtree(path)


def copy_file(src, des, permission=None):
    if src == des:
        return

    if os.path.exists(des):
        Warning("{} exists!".format(des))
    else:
        shutil.copy(src, des)
        if permission:
            os.chmod(des, permission)

def copy_file_force(src, des, permission=None):
    if src == des:
        return

    if os.path.exists(des):
        os.remove(des)
    
    shutil.copy(src, des)
    if permission:
        os.chmod(des, permission)


def copy_all(src, des, permission=None):
    if src == des:
        Warning("Source and Destination are same {}!!!".format(des))
        return False

    if not os.path.exists(src):
        return False

    copied = False
    for o in glob.glob(os.path.join(src, '*')):
        if os.path.isdir(o):
            copy_tree(
                o,
                os.path.join(des, os.path.basename(o)),
                permission=permission)
        else:
            copy_file(
                o,
                os.path.join(des, os.path.basename(o)),
                permission=permission)
        copied = True
    return copied


def copy_tree(src, des, permission=None):
    if src == des:
        return

    if os.path.exists(des):
        Warning("{} exists!".format(des))
    else:
        try:
            shutil.copytree(src, des, symlinks=True)
        except Exception as e:
            raise(e)
        if permission:
            os.chmod(des, permission)
